package com.ihrm.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther chongxiongwei
 * @create 2020-06-09-17:30
 */
@RestController
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);
    @GetMapping("/user/home")
    public String home(){
        return "访问主页成功";
    }

    @PostMapping("/user")
    public String add(){
        return "添加用户成功";
    }
    @GetMapping("/user")
    public String find(){
        return "查询用户成功";
    }

    @GetMapping("/login")
    public String login(String username, String password){
        logger.info("*******Username:*********{}",username);
        logger.info("*******Password:*********{}",password);
        try {
            /**
             * 密码加密
             *   shiro md5hash 加密
             *      参数一  源数据
             *      参数二  盐值
             *      参数三  加密次数
             */
            Md5Hash md5PassWord = new Md5Hash(password,username,3);
            logger.info("*******md5PassWord:*********{}",md5PassWord);
            // 根据username和password构造登录令牌
            UsernamePasswordToken upToken = new UsernamePasswordToken(username,password);
            Subject subject = SecurityUtils.getSubject();
            //调用subject进行登录
            subject.login(upToken);
            return "登录成功";
        }catch (Exception e){
            System.out.println(e);
            return "用户名或密码错误";
        }


    }

    @GetMapping("/autherror")
    public String autherror(int code){
        return code==1?"未登录":"未授权";
    }
}
